/*
 *使用 fmp 自己的数据进行过滤
 * @Author: mikey.zhaopeng
 * @Date:   2016-04-25 16:46:19
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 16:17:12
 */

'use strict';
define([
    '../../../framework/base/baseView',
    '../../../../modules/model/currency',
    '../../../../modules/model/currencies',
    'text!../tpl/fbFilter.html'
], function(
    BaseView,
    currency,
    currencies,
    tpl
) {
    function me() {
        BaseView.apply(this, arguments);
        var self = this;

        this.init = function($parent, meta, feed) {
            this.$parent = $parent;
            this.meta = meta;
            this.feed = feed;
            this.render();
        };
        this.render = function() {
            self.$parent.find('.fb-filter').append(I18N.parse(tpl, 'sets'));
            self.$parent.find('.fb-filter .filter-and:first').hide();
            self.$root = self.$parent.find('.fb-filter .form-group-filter:last')
            self.$category = self.$root.find('select[name=category]');
            self.$operas = self.$root.find('select[name=operas]');
            self.$currency = self.$root.find('select[name=curreny]');
            self.$date = self.$root.find('select[name=date]');
            self.$input = self.$root.find('.form-group-input');
            self.$category.empty().html(self.getCategoryHtml()).select2();
            self.event();
            self.$root.data('filter', self);
        }
        this.event = function() {
            self.$category.on('change', $.proxy(self.renderOperas, self));
            self.$category.trigger('change');
        }

        this.renderOperas = function(e) {
            var key = self.$category.val();
            var category = self.category = _.where(self.meta.fields, { key: key })[0];
            var operasHtml = self.getOperasHtml(self.meta.operas[category.field.type]);
            self.$operas.empty().html(operasHtml).select2({ minimumResultsForSearch: Infinity });
            self.$currency.parent().toggleClass('hidden', category.field.type != 'Currency');
            self.$date.parent().toggleClass('hidden', category.field.data_type != 'pixel');
            if (category.field.type == 'Currency') {
                var currencyHtml = self.getCurrencyHtml(currency[I18N.language]);
                self.$currency.empty().html(currencyHtml).select2();
                self.$currency.val(self.feed.currency).trigger('change').prop("disabled", true);
                self.$input.empty().html('<input type="text" name="input" class="form-control">');
                self.$input.find('input').numeral({ 'scale': 2 });
            } else if (category.field.type == 'Number') { //数字类型
                self.$input.empty().html('<input type="text" name="input" class="form-control">');
                self.$input.find('input').numeral({ 'scale': 2 });
            } else if (category.field.type == 'String') {
                if (category.field.value && category.field.value.length > 0) {
                    var option = '<select multiple="multiple" class="form-group-select2 select2-tags" style="width:100%">';
                    _.each(category.field.value, function(el) {
                        el = el.trim();
                        option = option + '<option value="' + _.escape(el) + '">' + self.translate(el) + '</option>';
                    });
                    option = option + '</select>'
                    self.$input.empty().html(option);
                    self.$input.find('select').select2();
                } else {
                    var option = '<select multiple="multiple" class="form-group-select2 select2-tags" style="width:100%"></select>';
                    self.$input.empty().html(option);
                    self.$input.find('select').select2({ tags: true });
                }
            } else if (category.field.type == 'Action') {
                self.$input.empty().html('<input type="text" name="input" class="form-control">');
                self.$input.find('input').numeral({ 'scale': 2 });
                self.$operas.on('change', function(e) {
                    if ($(this).val() == 'gt_lt') {
                        self.$input.empty().html('<div class="form-inline"> <div class="form-group" style="width: 50%; ">  <input type="input" class="form-control" name="gt-val" style="width: 100%; "> </div> <div class="form-group" style="width: 49%; ">  <input type="input" name="lt-val" class="form-control" style="width: 100%; "> </div> </div>');
                        self.$input.find('input[name="gt-val"]').numeral({ 'scale': 2 });
                        self.$input.find('input[name="lt-val"]').numeral({ 'scale': 2 });
                    } else {
                        self.$input.empty().html('<input type="text" name="input" class="form-control">');
                        self.$input.find('input').numeral({ 'scale': 2 });
                    }
                })
            } else if (category.field.type == 'EffectiveDate') { //促销价格只有isNull或者isNotNull
                self.$input.empty();
            }

            if (category.field.data_type == 'pixel') { //如果是 pixel ,都加上时间日期
                self.$date.removeClass('hidden').select2();
                self.bindDateSelect2();
            }
        }

        this.bindDateSelect2 = function() {
            var $dateSelect2 = self.$date.data('select2');
            $dateSelect2.on('results:message', function(message) {
                if (message.message == "noResults") {
                    var val = $dateSelect2.$dropdown.find('input').val();
                    self.$date.append('<option value="' + val + '">' + I18N.getText('sets', 'dateRangesX', val) + '</option>');
                    self.$date.select2("close");
                    self.$date.select2("open");
                    $dateSelect2.$dropdown.find('input').val(val).trigger('input');
                }
            });
            $dateSelect2.$dropdown.find('input.select2-search__field').numeral({ 'scale': 0 });
        }


        /**
         * 生成 category
         *
         * @method     getCategoryHtml
         */
        this.getCategoryHtml = function() {
            var t = '';
            _.each(self.meta.fields, function(el) {
                t = t + '<option value="' + el.key + '">' + self.translate(el.key) + '</option>';
            });
            return t;
        }

        /**
         * 生成 operas
         *
         * @method     getFilters
         */
        this.getOperasHtml = function(operas) {
            var t = '';
            _.each(operas, function(el) {
                t = t + '<option value="' + el + '">' + self.translate(el) + '</option>';
            });
            return t;
        }


        /**
         * 生成 currency
         *
         * @method     getFilters
         */
        this.getCurrencyHtml = function(currencies) {
            var t = '';
            _.each(currencies, function(el) {
                t = t + '<option value="' + el.unit + '">' + el.unit + ' - ' + el.name + '</option>';
            });
            return t;
        }

        /**
         * { 验证参数 }
         *
         * @method     validateParams
         */
        this.validateParams = function() {
            var category = self.category;
            if (category.field.type == 'Currency') {
                var val = self.$input.find('input').val();
                if (val.length == 0) {
                    self.remindNotNull(self.$input.find('input'));
                    return true;
                }
            } else if (category.field.type == 'Number') {
                var val = self.$input.find('input').val();
                if (val.length == 0) {
                    self.remindNotNull(self.$input.find('input'));
                    return true;
                }
            } else if (category.field.type == 'String') {
                var tags = self.$input.find('select').val();
                if (tags == null || tags.length == 0) {
                    self.remindNotNull(self.$input);
                    return true;
                }
            } else if (category.field.type == 'Action') {
                if (self.$operas.val() == 'gt_lt') {
                    var gtVal = self.$input.find('input[name=gt-val]').val();
                    if (gtVal.length == 0) {
                        self.remindNotNull(self.$input.find('input[name=gt-val]'));
                        return true;
                    }
                    var ltVal = self.$input.find('input[name=lt-val]').val();
                    if (ltVal.length == 0) {
                        self.remindNotNull(self.$input.find('input[name=lt-val]'));
                        return true;
                    }
                } else {
                    var val = self.$input.find('input').val();
                    if (val.length == 0) {
                        self.remindNotNull(self.$input.find('input'));
                        return true;
                    }
                }
            } else if (category.field.type == 'EffectiveDate') { //促销价格只有isNull或者isNotNull
                //因为没有 input 故,不做处理
            }
            return false;
        }

        this.remindNotNull = function($dom) {
            $dom.testRemind(I18N.getText('sets', 'notNull'));
            $dom.focus()
        }

        this.getParams = function() {
            if (self.validateParams()) {
                return true;
            }
            var paramsArr = [];
            var params = { or: [] }
            var category = self.category;
            if (category.field.type == 'Currency') {
                var val = self.$input.find('input').val();
                var price = {
                    "data_type": category.field.data_type
                }
                price[self.$category.val()] = {};
                price[self.$category.val()][self.$operas.val()] = parseInt(currencies[self.feed.currency] * val);

                var cur = {
                    or: [{
                        "data_type": category.field.data_type,
                        currency: {
                            eq: self.$currency.val()
                        }
                    }]
                }
                params.or.push(price);
                paramsArr.push(cur);
            } else if (category.field.type == 'Number') {
                var val = self.$input.find('input').val();
                var data = {
                    "data_type": category.field.data_type
                }
                data[self.$category.val()] = {};
                data[self.$category.val()][self.$operas.val()] = val;
                params.or.push(data);
            } else if (category.field.type == 'String') {
                var tags = self.$input.find('select').val();
                _.each(tags, function(tag) {
                    var data = {
                        "data_type": category.field.data_type
                    }
                    data[self.$category.val()] = {};
                    if (self.$operas.val() == 'is_any' || self.$operas.val() == 'is_not_any') {
                        data[self.$category.val()][self.$operas.val()] = [tag];
                    } else {
                        data[self.$category.val()][self.$operas.val()] = tag;
                    }
                    params.or.push(data);
                });
            } else if (category.field.type == 'Action') {
                var val = self.$input.find('input').val();
                if (self.$operas.val() == 'gt_lt') {
                    var data = {
                        "data_type": category.field.data_type,
                        "event": {
                            "event_name": self.$category.val(),
                            date: {
                                date_preset: (self.$date.val() * 1 + 1)
                            },
                            "actions": {
                                "gt": self.$input.find('input[name=gt-val]').val(),
                                "lt": self.$input.find('input[name=lt-val]').val()
                            }
                        }
                    }
                    params.or.push(data);
                } else {
                    var data = {
                        "data_type": category.field.data_type
                    }
                    data.event = {
                        event_name: self.$category.val(),
                        date: {
                            date_preset: (self.$date.val() * 1 + 1)
                        },
                        actions: {}
                    }
                    data.event.actions[self.$operas.val()] = val;
                    params.or.push(data);
                }
            } else if (category.field.type == 'EffectiveDate') { //促销价格只有isNull或者isNotNull
                var data = {
                    "data_type": category.field.data_type
                }
                data[self.$category.val()] = {};
                data[self.$category.val()][self.$operas.val()] = self.$operas.val();
                params.or.push(data);
            }
            paramsArr.push(params);
            return paramsArr;
        }


        /**
         * { 翻译 }
         */
        this.translate = function(key) {
            var keyTmp = key.replaceAll(' ', '_'); //去除空格
            var text = I18N.getText('sets', keyTmp);
            if (self.kit.isBlank(text)) { //如果没有翻译,则返回原来的值
                return key;
            }
            return text;
        }

    }
    return me;
});